using System;
using System.IO;
using System.Text.Json;
using GitProjectManager.Models;

namespace GitProjectManager.Services
{
    public class ConfigService
    {
        private static readonly string ConfigDirectory = 
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GitProjectManager");
        
        private static readonly string ConfigFilePath = 
            Path.Combine(ConfigDirectory, "config.json");

        public AppConfig LoadConfig()
        {
            try
            {
                if (!File.Exists(ConfigFilePath))
                {
                    return CreateDefaultConfig();
                }

                var json = File.ReadAllText(ConfigFilePath);
                return JsonSerializer.Deserialize<AppConfig>(json) ?? CreateDefaultConfig();
            }
            catch (Exception)
            {
                return CreateDefaultConfig();
            }
        }

        public void SaveConfig(AppConfig config)
        {
            try
            {
                Directory.CreateDirectory(ConfigDirectory);
                var options = new JsonSerializerOptions { WriteIndented = true };
                var json = JsonSerializer.Serialize(config, options);
                File.WriteAllText(ConfigFilePath, json);
            }
            catch (Exception ex)
            {
                // 处理保存错误
                System.Diagnostics.Debug.WriteLine($"保存配置失败: {ex.Message}");
            }
        }

        private AppConfig CreateDefaultConfig()
        {
            var config = new AppConfig();
            
            // 设置默认扫描路径
            var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            config.ScanSettings.ScanPaths = new List<string>
            {
                Path.Combine(userProfile, "Documents"),
                Path.Combine(userProfile, "Desktop"),
                Path.Combine(userProfile, "source"),
                Path.Combine(userProfile, "dev"),
                Path.Combine(userProfile, "projects"),
                Path.Combine(userProfile, "workspace"),
                "D:\\",
                "E:\\",
                "F:\\"
            };

            return config;
        }
    }
}